<template>
  <div class="vial-list">
    <h2 class="page-title">Vial Management</h2>

    <!-- Search and Filter -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="Keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="Search vial ID/donor"
            clearable
            @clear="handleSearch"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="searchForm.status" placeholder="Select status" clearable style="width: 150px">
            <el-option label="Available" value="Available" />
            <el-option label="Reserved" value="Reserved" />
            <el-option label="Used" value="Used" />
            <el-option label="Discarded" value="Discarded" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            Search
          </el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>Vial List</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            Add Vial
          </el-button>
        </div>
      </template>

      <!-- Table -->
      <el-table
        v-loading="loading"
        :data="vialList"
        style="width: 100%"
      >
        <el-table-column prop="vial_id" label="Vial ID" width="80" />
        <el-table-column prop="donor_code" label="Donor Code" width="120" />
        <el-table-column prop="donor_name" label="Donor Name" width="120" />
        <el-table-column prop="collection_date" label="Collection Date" width="120">
          <template #default="{ row }">
            {{ formatDate(row.collection_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="motility_percent" label="Motility (%)" width="100" />
        <el-table-column prop="sperm_count_mil" label="Sperm Count (M)" width="120" />
        <el-table-column prop="status" label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storage_location" label="Storage Location" width="200" />
        <el-table-column label="Actions" width="280">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              Edit
            </el-button>
            <el-button
              type="info"
              link
              @click="handleDiscard(row)"
              :disabled="row.status === 'Reserved' || row.status === 'Discarded' || row.status === 'Used'"
            >
              Discard
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="!row.can_delete"
              :title="row.status === 'Discarded' && !row.can_delete ? 'This vial has been used in orders and cannot be deleted' : 
                      row.status !== 'Discarded' ? 'Only discarded vials can be deleted' : ''"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
      >
        <el-form-item label="Donor" prop="donor_id">
          <el-select
            v-model="formData.donor_id"
            placeholder="Select donor"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="donor in donorList"
              :key="donor.donor_id"
              :label="`${donor.donor_code} - ${donor.full_name}`"
              :value="donor.donor_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Collection Date" prop="collection_date">
          <el-date-picker
            v-model="formData.collection_date"
            type="date"
            placeholder="Select date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="Motility (%)" prop="motility_percent">
          <el-input-number v-model="formData.motility_percent" :min="0" :max="100" :precision="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="Sperm Count (M)" prop="sperm_count_mil">
          <el-input-number v-model="formData.sperm_count_mil" :min="0" :precision="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="Status" prop="status">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="Available" value="Available" />
            <el-option label="Reserved" value="Reserved" />
            <el-option label="Used" value="Used" />
            <el-option label="Discarded" value="Discarded" />
          </el-select>
        </el-form-item>
        <el-form-item label="Storage Location" prop="storage_location">
          <el-input v-model="formData.storage_location" placeholder="e.g., Tank A, Rack 5, Box 3" />
        </el-form-item>
        <el-form-item label="Quarantine Release" prop="quarantine_release_date">
          <el-date-picker
            v-model="formData.quarantine_release_date"
            type="date"
            placeholder="Select date"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { vialAPI, donorAPI } from '@/api'

// Search form
const searchForm = reactive({
  keyword: '',
  status: ''
})

// Pagination
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Data lists
const vialList = ref([])
const donorList = ref([])
const loading = ref(false)

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('Add Vial')
const formRef = ref(null)
const formData = reactive({
  vial_id: null,
  donor_id: null,
  collection_date: '',
  motility_percent: null,
  sperm_count_mil: null,
  status: 'Available',
  storage_location: '',
  quarantine_release_date: ''
})

// Form validation rules
const formRules = {
  donor_id: [{ required: true, message: 'Please select donor', trigger: 'change' }],
  collection_date: [{ required: true, message: 'Please select collection date', trigger: 'change' }],
  motility_percent: [{ required: true, message: 'Please enter motility', trigger: 'blur' }],
  sperm_count_mil: [{ required: true, message: 'Please enter sperm count', trigger: 'blur' }],
  status: [{ required: true, message: 'Please select status', trigger: 'change' }],
  storage_location: [{ required: true, message: 'Please enter storage location', trigger: 'blur' }]
}

// Load donor list (load all active donors for adding vials)
const loadDonors = async () => {
  try {
    const data = await donorAPI.getList({ 
      is_active: 'true',
      pageSize: 1000  // Load enough donors
    })
    donorList.value = data.data || []
  } catch (error) {
    console.error('Failed to load donor list', error)
  }
}

// Load list data
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const data = await vialAPI.getList(params)
    vialList.value = data.data || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

// Search
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Page change (do not reset page number)
const handlePageChange = () => {
  loadData()
}

// Reset
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: ''
  })
  handleSearch()
}

// Add
const handleAdd = () => {
  dialogTitle.value = 'Add Vial'
  Object.assign(formData, {
    vial_id: null,
    donor_id: null,
    collection_date: '',
    motility_percent: null,
    sperm_count_mil: null,
    status: 'Available',
    storage_location: '',
    quarantine_release_date: ''
  })
  dialogVisible.value = true
}

// Edit
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Vial'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// Discard vial (change status to Discarded)
const handleDiscard = async (row) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to discard vial ${row.vial_id}? This vial will become unavailable.`,
      'Confirm Discard',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await vialAPI.update(row.vial_id, { status: 'Discarded' })
    ElMessage.success('Vial discarded')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to discard')
    }
  }
}

// Delete vial (permanent deletion)
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to permanently delete vial ${row.vial_id}? This action cannot be undone!`,
      'Danger',
      {
        confirmButtonText: 'Confirm Delete',
        cancelButtonText: 'Cancel',
        type: 'error'
      }
    )
    await vialAPI.delete(row.vial_id)
    ElMessage.success('Deleted successfully')
    loadData()
  } catch (error) {
    // User cancelled operation, no message
    // Other errors (like 400) are already shown by request interceptor
    if (error === 'cancel') {
      // User cancelled, silent handling
    }
  }
}

// Submit form
const handleSubmit = async () => {
  await formRef.value.validate()
  try {
    if (formData.vial_id) {
      await vialAPI.update(formData.vial_id, formData)
      ElMessage.success('Updated successfully')
    } else {
      await vialAPI.create(formData)
      ElMessage.success('Created successfully')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('Operation failed')
  }
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

// Get status type
const getStatusType = (status) => {
  const typeMap = {
    'Available': 'success',
    'Reserved': 'warning',
    'Used': 'info',
    'Discarded': 'info'  // Discarded and Used have same color (gray)
  }
  return typeMap[status] || ''
}

onMounted(() => {
  loadDonors()
  loadData()
})
</script>

<style scoped>
.vial-list {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
